<script setup>
	import {getCurrentInstance, onBeforeUnmount, onMounted, ref} from "vue";
	import {getToken} from "@/utils/auth";
	import {addStructure, getStructureByKey, updStructure} from "@/api/company/structure";
	import { getPositionPage } from "@/api/company/position";
	const { proxy } = getCurrentInstance();
	import emitter from "@/utils/mitt";
	
	const props = defineProps({
		rowId: {
			type: [Number, String],
			default: null
		}
	})
	
	const formData = ref({
		desc: null,
		engageWork: null,
		id: null,
		isTop: 0,
		isView: 1,
		photoFileIds: [],
		fileUrl: null,
		politicsStatus: null,
		positionId: null,
		sort: null,
		technicalTitles: null,
		userName: null,
		work: null
	});
	const rules = ref({
		userName: [{required: true, message: '请输入人员姓名', trigger: 'change'}],
		positionId: [{required: true, message: '请选择协会职位', trigger: 'change'}],
		fileUrl: [{required: true, message: '请上传人员照片', trigger: 'change'}],
		politicsStatus: [{required: true, message: '请输入政治面貌', trigger: 'change'}],
		work: [{required: true, message: '请输入工作单位', trigger: 'change'}],
	});
	
	const positionOption = ref([])
	const getPositionOption = async () => {
		const res = await getPositionPage({ pageNum: 1, pageSize: 999 })
		try {
			if(res.code === 200) {
				positionOption.value = res.data.records
			}
		}
		catch(e) {
			console.log(e);
		}
	}

	const getData = async () => {
		const res = await getStructureByKey({id: props.rowId})
		if(res.code === 200) {
			formData.value.desc = res.data.desc,
			formData.value.engageWork = res.data.engageWork,
			formData.value.id = res.data.id,
			formData.value.isTop = res.data.isTop,
			formData.value.isView = res.data.isView,
			formData.value.fileUrl = res.data.photoFiles?.length ? res.data.photoFiles[0].accessUrl : null
			formData.value.photoFileIds = res.data.photoFiles?.length ? [res.data.photoFiles[0].id] : []
			formData.value.politicsStatus = res.data.politicsStatus,
			formData.value.positionId = res.data.positionId,
			formData.value.sort = res.data.sort,
			formData.value.technicalTitles = res.data.technicalTitles,
			formData.value.userName = res.data.userName,
			formData.value.work = res.data.work
		}
	}
	
	const submit = () => {
		proxy.$refs.elForm.validate(async valid => {
			if(valid) {
				const params = formData.value
				let res
				params.id !== null && params !== '' ? res = await updStructure(params) : res = await addStructure(params)
				try {
					if(res.code === 200) {
						proxy.$modal.msgSuccess('操作成功')
						cancel(true)
					}
					else {
						proxy.$modal.msgError(res.msg)
					}
				}
				catch(e) {
					console.log(e);
					proxy.$modal.msgError(JSON.stringify(e))
				}
			}
		})
	}
	
	const cancel = (ifSubmit = false) => {
		emitter.emit('closeEdit', ifSubmit)
	}
	
	onMounted(() => {
		getPositionOption()
		if(props.rowId) {
			getData();
		}
	})

	// 图片上传
	const fileAction = import.meta.env.VITE_APP_BASE_API + "/organization/addPhotoImg";
	const clearFile = () => {
		formData.value.fileUrl = null;
		formData.value.photoFileIds = [];
		proxy.$refs["fileId"].clearFiles();
	};

	const photoBeforeUpload = (file) => {
		let isRightSize = file.size / 1024 / 1024 < 20;
		if (!isRightSize) {
			proxy.$modal.msgError("文件大小超过 20MB");
		}
		return isRightSize;
	};
	const handleRemove = (file, fileList) => {
		formData.value.fileUrl = null;
		formData.value.photoFileIds = [];
	};
	const uploadSuccess = (response, file, fileList) => {
		if (response.code === 200) {
			formData.value.photoFileIds = response.data.id ? [response.data.id] : [];
			formData.value.fileUrl = response.data.accessUrl;
		} else {
			formData.value.photoFileIds = [];
			formData.value.fileUrl = null;
		}
	};
	
</script>

<template>
	<div class="dialogContent">
		<el-form ref="elForm" :model="formData" :rules="rules" label-width="100px" :size="'default'">
			<el-form-item label="人员姓名" prop="userName">
				<el-input v-model="formData.userName" :style="{ width: '100%' }" clearable placeholder="请输入人员姓名"></el-input>
			</el-form-item>
			<el-form-item label="协会职位" prop="positionId">
				<el-select v-model="formData.positionId" clearable placeholder="请选择职位">
					<el-option v-for="item in positionOption" :key="item.id" :label="item.name" :value="item.id"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="人员照片" prop="fileUrl">
				<el-upload
					ref="fileId"
					:accept="'.jpg,.jpeg,.png'"
					:action="fileAction"
					:before-upload="photoBeforeUpload"
					:headers="{
						Authorization: 'Bearer ' + getToken(),
					}"
					:limit="1"
					:list-type="'picture'"
					:on-remove="handleRemove"
					:on-success="uploadSuccess"
					:show-file-list="false">
					<el-button :disabled="formData.fileUrl" icon="Upload" :size="'small'" type="primary">
						上传照片
					</el-button>
					<el-button size="small" type="warning" @click.stop="clearFile">清空上传</el-button>
				</el-upload>
			</el-form-item>
			<el-form-item v-if="formData.fileUrl" prop="fileUrl">
				<el-image :preview-src-list="[formData.fileUrl]" :src="formData.fileUrl" style="width: 100px; height: 100px"> </el-image>
			</el-form-item>
			<el-form-item label="政治面貌" prop="politicsStatus">
				<el-input v-model="formData.politicsStatus" clearable placeholder="请输入政治面貌"></el-input>
			</el-form-item>
			<el-form-item label="工作单位" prop="work">
				<el-input v-model="formData.work" clearable placeholder="请输入工作单位"></el-input>
			</el-form-item>
			<el-form-item label="技术职称" prop="technicalTitles">
				<el-input v-model="formData.technicalTitles" clearable placeholder="请输入技术职称"></el-input>
			</el-form-item>
			<el-form-item label="从事工作" prop="engageWork">
				<el-input v-model="formData.engageWork" clearable placeholder="请输入从事工作"></el-input>
			</el-form-item>
			<el-form-item label="简述" prop="desc">
				<el-input
					v-model="formData.desc"
					:autosize="{ minRows: 4, maxRows: 4 }"
					:style="{ width: '100%' }"
					placeholder="请输入简述"
					type="textarea"
				/>
			</el-form-item>
			<el-form-item label="是否置顶" prop="isTop">
				<el-switch v-model="formData.isTop" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否"></el-switch>
			</el-form-item>
			<el-form-item label="排序值" prop="sort">
				<el-input-number v-model="formData.sort" clearable placeholder="排序值" :step="1" :min="0"></el-input-number>&nbsp;&nbsp;排序值越小越靠前
			</el-form-item>
			<el-form-item label="是否显示" prop="isView">
				<el-switch v-model="formData.isView" :active-value="1" :inactive-value="0" active-text="显示" inactive-text="不显示"></el-switch>
			</el-form-item>
		</el-form>
		<div class="buttonList">
			<el-button class="button" type="primary" @click="submit">提交</el-button>
			<el-button class="button" @click="cancel">取消</el-button>
		</div>
	</div>
</template>

<style lang="scss" scoped>
	.dialogContent {
		overflow: auto;
	}
	.buttonList {
		display: flex;
		justify-content: center;
		margin-top: 20px;
	}
</style>
